package com.ruoyi.web.controller.wechat;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wechat.domain.WxUser;
import com.ruoyi.wechat.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 微信用户
 *
 * @author yan
 */
@Slf4j
@RestController
@RequestMapping("/wechat/wxUser")
@RequiredArgsConstructor
@Api(tags = {"公众号用户"})
public class WxUserController extends BaseController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private WxUserService wxUserService;

    private final WxMpService wxMpService;

    @GetMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息")
    public AjaxResult getUserInfo(@RequestParam("appid") String appid, @RequestParam("openid") String openid) {
        this.wxMpService.switchoverTo(appid);
        WxUser wxUser = wxUserService.getById(openid);
        logger.info("用户信息:{}", wxUser);
        return AjaxResult.success("用户信息", wxUser);
    }

    /**
     * 分页查询
     *
     * @param page   分页对象
     * @param wxUser 微信用户
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public AjaxResult getWxUserPage(Page page, WxUser wxUser, String tagId) {
        logger.info("查询条件:{}", wxUser);
        if (StringUtils.isBlank(wxUser.getNickname())) {
            wxUser.setNickname(null);
        }
        if (StringUtils.isBlank(wxUser.getRemark())) {
            wxUser.setRemark(null);
        }
        Wrapper<WxUser> queryWrapper;
        if (StringUtils.isNotBlank(tagId)) {
            queryWrapper = Wrappers.lambdaQuery(wxUser)
                    .and(wrapper -> wrapper
                            .eq(WxUser::getTagidList, "[" + tagId + "]")
                            .or()
                            .like(WxUser::getTagidList, "," + tagId + ",")
                            .or()
                            .likeRight(WxUser::getTagidList, "[" + tagId + ",")
                            .or()
                            .likeLeft(WxUser::getTagidList, "," + tagId + "]"));
        } else if (StrUtil.isNotBlank(wxUser.getNickname())) {
            String nickName = wxUser.getNickname();
            wxUser.setNickname(null);
            queryWrapper = Wrappers.lambdaQuery(wxUser)
                    .like(WxUser::getNickname, nickName);
        } else if (StrUtil.isNotBlank(wxUser.getRemark())) {
            String remark = wxUser.getRemark();
            wxUser.setRemark(null);
            queryWrapper = Wrappers.lambdaQuery(wxUser)
                    .like(WxUser::getRemark, remark);
        } else {
            queryWrapper = Wrappers.lambdaQuery(wxUser);
        }
        logger.info("查询用户的数据:{}", queryWrapper);
        Page page1 = wxUserService.page(page, queryWrapper);
        logger.info("用户数组：{}",page1.getRecords());
        return AjaxResult.success(page1);
    }

    @PostMapping("/synchron/{appid}")
    @ApiOperation(value = "同步微信用户")
    public AjaxResult synchron(@PathVariable String appid) {
        logger.info("获取{}公众号的用户信息", appid);
        wxUserService.syncWxUsers(appid);
        return AjaxResult.success();
    }

    /**
     * 修改微信用户备注
     *
     * @param wxUser
     * @return
     */
    @ApiOperation(value = "修改微信用户备注")
    @PutMapping("/remark")
    public AjaxResult remark(@RequestBody WxUser wxUser) {
        try {
            return AjaxResult.success(wxUserService.updateRemark(wxUser));
        } catch (WxErrorException e) {
            e.printStackTrace();
            logger.error("修改微信用户备注失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 打标签
     *
     * @param data
     * @return
     */
    @ApiOperation(value = "打标签")
    @PutMapping("/tagid-list")
    public AjaxResult tagIdList(@RequestBody JSONObject data) {
        try {
            String appId = data.getStr("appid");
            String taggingType = data.getStr("taggingType");
            String tagIds = data.getStr("tagIds");
            String[] tagIdsArray = tagIds.split(",");
            JSONArray openIdsArray = data.getJSONArray("openIds");
            String[] openIds = openIdsArray.toArray(new String[0]);

            for (String tagId : tagIdsArray) {
                wxUserService.tagging(taggingType, Long.valueOf(tagId), openIds, appId);
            }
            return AjaxResult.success();
        } catch (WxErrorException e) {
            e.printStackTrace();
            logger.error("修改微信用户标签失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通过id查询微信用户
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询微信用户")
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable("id") String id) {
        return AjaxResult.success(wxUserService.getById(id));
    }

    /**
     * 新增微信用户
     *
     * @param wxUser 微信用户
     * @return R
     */
    @ApiOperation(value = "新增微信用户")
    @PostMapping
    public AjaxResult save(@RequestBody WxUser wxUser) {
        return AjaxResult.success(wxUserService.save(wxUser));
    }

    /**
     * 修改微信用户
     *
     * @param wxUser 微信用户
     * @return R
     */
    @ApiOperation(value = "修改微信用户")
    @PutMapping
    public AjaxResult updateById(@RequestBody WxUser wxUser) {
        return AjaxResult.success(wxUserService.updateById(wxUser));
    }

    /**
     * 通过id删除微信用户
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除微信用户")
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable String id) {
        return AjaxResult.success(wxUserService.removeById(id));
    }


}
